package servlet;

import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addUser")
public class UserPrepareAddServlet extends HttpServlet {
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String account = request.getParameter("addAccount");
		String password = request.getParameter("addPwd");
		String realName = request.getParameter("addUserRealName");
		String nickname = request.getParameter("addNickName");
		Integer role = Integer.parseInt(request.getParameter("addRole"));
		UserDao dao = new UserDao();
		int retSureAccount = dao.sure_user(account);
		if(retSureAccount >= 1){
			//用户名已存在
			request.getSession().setAttribute("errorMsg", "用户名已存在");
			request.getRequestDispatcher("./userList").forward(request, response);
			return;
		}
		int retInsertUser = dao.regist(account,password,realName,nickname,role);
		if(retInsertUser >= 1){
			request.getSession().setAttribute("successMsg", "新增成功！");
			request.getRequestDispatcher("./userList").forward(request, response);
			return;
		}else{
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}
	}
}
